// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/benchmark.h>
#include <melon/init/init.h>
#include <string>

#include <pollux/expression/vector_readers.h>
#include <pollux/functions/registerer.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/common/strings/string_view.h>

namespace kumo::pollux::exec {

namespace {

// The StringView has an optimization. If the string is small, then it is
// inlined(copied) on the stack within the StringView, instead of being
// referred to through a pointer.
// We still do write to the buffer in the current string writer always
// regardless of the string size, although it's not required in that case since
// the StringView have the date within its object memory.

template <typename T>
struct NotInlineStringFunc {
  template <typename OutT>
  void call(OutT& out, const int64_t& n) {
    out.append("Welcome to Pollux 2022!");
    out.append(std::to_string(n));
  }
};

template <typename T>
struct InlineStringFunc {
  template <typename OutT>
  void call(OutT& out, const int64_t& n) {
    out.append(std::to_string(n));
  }
};

template <typename T>
struct ArrayOfStringFunc {
  template <typename OutT>
  void call(OutT& out, const int64_t& n) {
    for (auto i = 0; i < n % 30; i++) {
      auto& item = out.add_item();
      item.append("welcome to the Pollux!!");
    }
  }
};

class StringWriterBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  StringWriterBenchmark() : FunctionBenchmarkBase() {
    register_function<NotInlineStringFunc, Varchar, int64_t>(
        {"not_inline_string"});

    register_function<InlineStringFunc, Varchar, int64_t>({"inline_string"});

    register_function<ArrayOfStringFunc, Array<Varchar>, int64_t>(
        {"array_of_string"});
  }

  vector_size_t size = 1000;

  auto makeInput() {
    std::vector<int64_t> inputData(size, 0);
    for (auto i = 0; i < size; i++) {
      inputData[i] = i;
    }

    auto input = vectorMaker_.row_vector({vectorMaker_.flat_vector(inputData)});
    return input;
  }

  size_t run(const std::string& functionName, size_t n) {
    melon::BenchmarkSuspender suspender;
    auto input = makeInput();
    auto exprSet =
        compileExpression(fmt::format("{}(c0)", functionName), input->type());
    suspender.dismiss();
    return doRun(exprSet, input, n);
  }

  size_t doRun(ExprSet& exprSet, const RowVectorPtr& row_vector, size_t n) {
    int cnt = 0;
    for (auto i = 0; i < n; i++) {
      cnt += evaluate(exprSet, row_vector)->size();
    }
    return cnt;
  }

  void test() {
    auto input = makeInput();

    // test not_inline_string
    {
      auto exprSet = compileExpression("not_inline_string(c0)", input->type());
      auto result = evaluate(exprSet, input);
      POLLUX_CHECK_EQ(result->size(), input->size(), "size test failed");

      auto* flatResult = result->as_flat_vector<StringView>();
      for (auto i = 0; i < input->size(); i++) {
        std::string expected = "Welcome to Pollux 2022!" + std::to_string(i);
        POLLUX_CHECK_EQ(
            flatResult->value_at(i), StringView(expected), "test failed");
      }
    }

    // test inline_string
    {
      auto exprSet = compileExpression("inline_string(c0)", input->type());
      auto result = evaluate(exprSet, input);
      POLLUX_CHECK_EQ(result->size(), input->size(), "size test failed");

      auto* flatResult = result->as_flat_vector<StringView>();
      for (auto i = 0; i < input->size(); i++) {
        std::string expected = std::to_string(i);
        POLLUX_CHECK_EQ(
            flatResult->value_at(i), StringView(expected), "test failed");
      }
    }

    // test array_of_string
    {
      auto exprSet = compileExpression("array_of_string(c0)", input->type());
      auto result = evaluate(exprSet, input);
      POLLUX_CHECK_EQ(result->size(), input->size(), "size test failed");

      DecodedVector decoded;
      SelectivityVector rows(result->size());
      decoded.decode(*result.get(), rows);

      exec::VectorReader<Array<Varchar>> reader(&decoded);

      for (auto i = 0; i < input->size(); i++) {
        auto arrayView = reader.readNullFree(i);
        POLLUX_CHECK_EQ(arrayView.size(), i % 30, "array size test failed");

        for (auto j = 0; j < i % 30; j++) {
          POLLUX_CHECK_EQ(
              arrayView[j], "welcome to the Pollux!!"_sv, "size test failed");
        }
      }
    }
  }
};

BENCHMARK_MULTI(not_inline_string) {
  StringWriterBenchmark benchmark;
  return benchmark.run("not_inline_string", 100);
}

BENCHMARK_MULTI(inline_string) {
  StringWriterBenchmark benchmark;
  return benchmark.run("inline_string", 100);
}

BENCHMARK_MULTI(array_of_string) {
  StringWriterBenchmark benchmark;
  return benchmark.run("array_of_string", 100);
}

} // namespace
} // namespace kumo::pollux::exec

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};

  kumo::pollux::exec::StringWriterBenchmark benchmark;
  benchmark.test();
  melon::runBenchmarks();
  return 0;
}
